import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}


@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    //此处把消息保存到内存中(一旦重启服务器,内存数据就没了)
    //更科学的方式,应该是保存到数据库中
    private List<Message> messageList = new ArrayList<>();
    //用来实现存档操作
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.读取请求的body,转换成Java对象
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        //2.得到message之后,把message保存到服务器中
        messageList.add(message);
        System.out.println("服务器收到message: "+ message );
        //3.返回响应(不太必要,主要是返回一个200 OK就行了,body可以没有)
        resp.setStatus(200);
        resp.getWriter().write("ok");
    }


    //用来实现读档操作
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //把我们内存中的这些Message,组织成json格式,返回到响应中.
        String respJson = objectMapper.writeValueAsString(messageList);
        //告诉浏览器,返回的响应的body是一个json格式.
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respJson);
    }
}
